import {
  apiLogin, apiGetOpenidByCode, apiNowOpenidInfo,
  apiUploadToken
} from '../other/api'

import { regeneratorRuntime } from '../other/bundle'

const apiLoginRes = () => {
  return {
    actionStatus: 'INIT',
    data: {}
  }
}

const minaLoginRes = () => {
  return {
    actionStatus: 'INIT',
    data: {}
  }
}

const uploadTokenRes = () => {
  return {
    actionStatus: 'INIT',
    data: {}
  }
}

const initState = {
  // UI
  uiSologan: '夫安装者，匠心传承',

  uiSystemService: {
    name: '系统客服名字',
    uiUserType: '系统客服职称',
    mobile: '000-00000000'
  },

  uiShowSidebar: false,

  minaSystemInfo: {},

  apiLoginRes: apiLoginRes(),

  minaLoginRes: minaLoginRes(),

  uploadTokenRes: uploadTokenRes(),

  randId: null,
  imageData: [],
  effectImages: []
}

export const initGlobal = data => {
  return async dispatch => {
    await dispatch({ data, type: 'INIT_GLOBAL', })
  }
}
export const showSidebar = data => {
  return async dispatch => {
    await dispatch({ data, type: 'SHOW_SIDEBAR', })
  }
}
export const hideSidebar = data => {
  return async dispatch => {
    await dispatch({ data, type: 'HIDE_SIDEBAR', })
  }
}
export const getSystemInfo = data => {
  return async dispatch => {
    const actionRes = await new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: res => {
          resolve(res)
        }, fail(err) {
          reject(err)
        }
      })
    })
    await dispatch({
      type: 'GET_SYSTEM_INFO',
      data: actionRes
    })
  }
}
export const setMinaUserInfo = data => ({
  type: 'SET_MINA_USER_INFO',
  data
})
export const initPageImageSelect = data => ({
  type: 'INIT_PAGE_IMAGE_SELECT',
  data
})
export const pageImageSelectSubmit = data => ({
  type: 'PAGE_IMAGE_SELECT_SUBMIT',
  data
})
export const prepareEffectImage = data => ({
  type: 'PREPARE_EFFECT_IMAGE',
  data
})

// export const resetPageImageSelect = data => ({
//   type: 'RESET_PAGE_IMAGE_SELECT',
//   data
// })
// export const setPageImageSelect = data => ({
//   type: 'SET_PAGE_IMAGE_SELECT',
//   data
// })

export const minaLogin = params => {
  return async dispatch => {
    let data = {
      actionStatus: 'PENDING'
    }
    try {
      // 先从本地取openid
      let openid = wx.getStorageSync('openid')

      if (!openid) {
        // step1 获取code
        const minaLoginRes = await new Promise((resolve, reject) => {
          wx.login({
            success(res) { resolve(res) },
            fail(res) { reject(res) }
          })
        })
        console.log('step1 res', minaLoginRes)

        // step2 获取openid
        const apiOpenidRes = await apiGetOpenidByCode({ code: minaLoginRes.code })
        console.log('step2 res', apiOpenidRes)
        openid = apiOpenidRes.data

        // 设置openid到本地
        wx.setStorageSync('openid', openid)
      }

      // step3 判断是否绑定
      const apiBindRes = await apiNowOpenidInfo({ openid })
      console.log('step3 res', apiBindRes)
      const replaceMobile = (mobile = '') => {
        let arr = String(mobile).split('').filter(i => i)
        arr.splice(3, 5, '****')
        return arr.join('')
      }
      // 绑定成功
      if (apiBindRes.apiCode === 200 && apiBindRes.apiStatus === 'SUCCESS' && apiBindRes.data && (apiBindRes.data['user_type'] == 1 || apiBindRes.data['user_type'] == 2)) {
        data = {
          actionStatus: 'SUCCESS',
          ...apiBindRes,
          data: {
            ...apiBindRes.data,

            // 模拟审核员
            // user_type: 1, // todo
            // uiUserType: '审核员',

            // 模拟店长
            // user_type: 2, // todo
            // uiUserType: '店长',

            // 正常流程
            uiUserType: ['审核员', '店长'][apiBindRes.data['user_type'] - 1],
            
            uiMobile: (apiBindRes.data.mobile && replaceMobile(apiBindRes.data.mobile)) || '',
          }
        }
      } else {
        // step4 发起业务登录
        const apiLoginRes = await apiLogin({ ...params, openid })
        console.log('step4 res', apiLoginRes)
        console.log(apiLoginRes.data)
        // 登录成功且绑定过的才行
        if (apiLoginRes.apiCode === 200 && apiLoginRes.apiStatus === 'SUCCESS' && (apiLoginRes.data['user_type'] == 1 || apiLoginRes.data['user_type'] == 2)) {
          console.log(apiLoginRes);
          data = {
            actionStatus: 'SUCCESS',
            ...apiLoginRes,
            data: {
              ...apiLoginRes.data,
              uiMobile: (apiLoginRes.data.mobile && replaceMobile(apiLoginRes.data.mobile)) || '',
              uiUserType: ['审核员', '店长', '师傅', ''][apiLoginRes.data['user_type'] - 1]
            }
          }
        } else {
          data = {
            actionStatus: 'FAILURE',
            ...apiLoginRes
          }
        }
      }
    } catch (error) {
      console.error('捕获异常', error)
      data = {
        actionStatus: 'FAILURE',
        ...error
      }
    }
    await dispatch({ data, type: 'SET_MINA_LOGIN' })
    return data;
  }
}

export const getUploadToken = params => {
  return async dispatch => {
    let data = {
      actionStatus: 'PENDING'
    }
    try {
      const apiRes = await apiUploadToken(params)
      if (apiRes.apiCode === 200 && apiRes.apiStatus === 'SUCCESS') {
        data = {
          actionStatus: 'SUCCESS',
          ...apiRes
        }
      } else {
        throw new Error('UNKNOW_ERROR ' + JSON.stringify(apiRes))
      }
    } catch (error) {
      console.error('捕获异常', error)
      data = {
        actionStatus: 'FAILURE',
        ...error
      }
    }
    await dispatch({ data, type: 'SET_UPLOAD_TOKEN' })
    return data;
  }
}

export const reducer = (state = initState, action) => {

  switch (action.type) {
    case 'PREPARE_EFFECT_IMAGE': {
      return {
        ...state,
        effectImages: action.data
      }
    }
    case 'INIT_PAGE_IMAGE_SELECT': {
      return {
        ...state,
        ...action.data
      }
    }
    case 'PAGE_IMAGE_SELECT_SUBMIT': {
      return {
        ...state,
        ...action.data
      }
    }
    // case 'RESET_PAGE_IMAGE_SELECT': {
    //   return {
    //     ...state,
    //     randId: null,
    //     imageData: []
    //   }
    // }
    // case 'SET_PAGE_IMAGE_SELECT': {
    //   const { imageData } = state
    //   const { index, multiple } = action.data
    //   if (!multiple) {
    //     imageData.map(i => i.checked = false)
    //   }
    //   imageData[index].checked = !imageData[index].checked
    //   return {
    //     ...state,
    //     imageData
    //   }
    // }
    case 'SET_MINA_LOGIN':
      return {
        ...state,
        minaLoginRes: action.data
      }
    case 'SET_MINA_USER_INFO':
      return {
        ...state,
        apiLoginRes: action.data
      }
    case 'GET_SYSTEM_INFO':
      return {
        ...state,
        minaSystemInfo: action.data
      }
    case 'INIT_GLOBAL':
      return {
        ...state,
        GLOBAL_INIT: action.data
      }
    case 'SHOW_SIDEBAR':
      return {
        ...state,
        uiShowSidebar: true
      }
    case 'HIDE_SIDEBAR':
      return {
        ...state,
        uiShowSidebar: false
      }
    case 'SET_UPLOAD_TOKEN':
      return {
        ...state,
        uploadTokenRes: action.data
      }
    default:
      return state
      break;
  }
}

export default {
  reducer,
  initGlobal,
  showSidebar,
  hideSidebar,
  getSystemInfo,
  setMinaUserInfo,
  minaLogin,
  getUploadToken,
  initPageImageSelect
}